package com.hskn.hss.module.elementtotal.service.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hskn.hss.core.annotation.DataScope;
import com.hskn.hss.core.domain.BaseEntity;
import com.hskn.hss.core.utils.spring.SpringUtils;
import com.hskn.hss.exception.HssException;
import com.hskn.hss.exception.ProgramTerminationException;
import com.hskn.hss.module.alarmcar.entity.AlarmCar;
import com.hskn.hss.module.alarmcar.mapper.AlarmCarMapper;
import com.hskn.hss.module.alarmperson.entity.AlarmPerson;
import com.hskn.hss.module.alarmperson.mapper.AlarmPersonMapper;
import com.hskn.hss.module.carviolation.entity.CarViolation;
import com.hskn.hss.module.carviolation.mapper.CarViolationMapper;
import com.hskn.hss.module.cases.entity.Cases;
import com.hskn.hss.module.cases.service.ICasesService;
import com.hskn.hss.module.depart.entity.SysDepart;
import com.hskn.hss.module.depart.mapper.SysDepartMapper;
import com.hskn.hss.module.dlbjviolation.entity.DlbjViolation;
import com.hskn.hss.module.dlbjviolation.mapper.DlbjViolationMapper;
import com.hskn.hss.module.elementtotal.iEnum.DTUEnum;
import com.hskn.hss.module.elementtotal.mapper.ElementTotalMapper;
import com.hskn.hss.module.elementtotal.service.ElementTotalService;
import com.hskn.hss.module.elementtotal.vo.*;
import com.hskn.hss.module.equiptype.entity.TlEquiptype;
import com.hskn.hss.module.equiptype.mapper.TlEquiptypeMapper;
import com.hskn.hss.module.kfkdtu.entity.KfkDtu;
import com.hskn.hss.module.kfkdtu.mapper.KfkDtuMapper;
import com.hskn.hss.module.kfkmanholecover.entity.KfkManholeCover;
import com.hskn.hss.module.kfkmanholecover.mapper.KfkManholeCoverMapper;
import com.hskn.hss.module.rptCarWork.entity.RptCarWork;
import com.hskn.hss.module.rptCarWork.mapper.RptCarWorkMapper;
import com.hskn.hss.module.rptEmployeeWork.entity.RptEmployeeWork;
import com.hskn.hss.module.rptEmployeeWork.mapper.RptEmployeeWorkMapper;
import com.hskn.hss.module.tlcar.entity.TlCar;
import com.hskn.hss.module.tlcar.mapper.TlCarMapper;
import com.hskn.hss.module.tlcar.vo.CarJobType;
import com.hskn.hss.module.tlcartype.entity.TlCarType;
import com.hskn.hss.module.tlcartype.mapper.TlCarTypeMapper;
import com.hskn.hss.module.tlchannel.entity.TlChannel;
import com.hskn.hss.module.tlchannel.mapper.TlChannelMapper;
import com.hskn.hss.module.tlemployee.entity.TlEmployee;
import com.hskn.hss.module.tlemployee.mapper.TlEmployeeMapper;
import com.hskn.hss.module.tlequip.entity.TlEquip;
import com.hskn.hss.module.tlequip.mapper.TlEquipMapper;
import com.hskn.hss.module.tlequip.service.ITlEquipService;
import com.hskn.hss.module.tlfacilities.entity.TlFacilities;
import com.hskn.hss.module.tlfacilities.mapper.TlFacilitiesMapper;
import com.hskn.hss.module.tlfacilities.service.ITlFacilitiesService;
import com.hskn.hss.module.tlfacilitietype.entity.TlFacilitiesType;
import com.hskn.hss.module.tlfacilitietype.mapper.TlFacilitiesTypeMapper;
import com.hskn.hss.module.tlfacilitietype.service.ITlFacilitiesTypeService;
import com.hskn.hss.module.tlfactypeitem.entity.TlFacilitiesTypeItems;
import com.hskn.hss.module.tlfactypeitem.service.ITlFacilitiesTypeItemsService;
import com.hskn.hss.module.tlopetation.entity.TlOperation;
import com.hskn.hss.module.tlopetation.mapper.TlOperationMapper;
import com.hskn.hss.module.tlthreshold.entity.TlThreshold;
import com.hskn.hss.module.tlthreshold.mapper.TlThresholdMapper;
import com.hskn.hss.module.tlthreshold.service.ITlThresholdService;
import com.hskn.hss.module.tlworktype.entity.TlWorkType;
import com.hskn.hss.module.tlworktype.mapper.TlWorkTypeMapper;
import com.hskn.hss.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author hskn
 * @since 2021-05-15
 */
@Slf4j
@Service
public class ElementTotalServiceImpl implements ElementTotalService {
    @Resource
    ElementTotalMapper elementTotalMapper;
    @Autowired
    ICasesService casesService;
    @Resource
    TlChannelMapper tlChannelMapper;
    @Autowired
    ITlFacilitiesTypeItemsService iTlFacilitiesTypeItemsService;
    @Autowired
    ITlFacilitiesService iTlFacilitiesService;
    @Autowired
    ITlFacilitiesTypeService iTlFacilitiesTypeService;
    @Resource
    private TlOperationMapper tlOperationMapper;
    @Autowired
    private ITlEquipService tlEquipService;
    @Resource
    private TlCarMapper tlCarMapper;
    @Resource
    private TlEquipMapper tlEquipMapper;
    @Resource
    private TlCarTypeMapper tlCarTypeMapper;
    @Resource
    private TlEmployeeMapper tlEmployeeMapper;
    @Resource
    private TlWorkTypeMapper tlWorkTypeMapper;
    @Resource
    private SysDepartMapper sysDepartMapper;
    @Resource
    private TlEquiptypeMapper tlEquiptypeMapper;
    @Resource
    private KfkDtuMapper kfkDtuMapper;
    @Resource
    private KfkManholeCoverMapper kfkManholeCoverMapper;
    @Resource
    private RptCarWorkMapper rptCarWorkMapper;
    @Resource
    private AlarmCarMapper alarmCarMapper;
    @Resource
    private CarViolationMapper carViolationMapper;
    @Resource
    private RptEmployeeWorkMapper rptEmployeeWorkMapper;
    @Resource
    private AlarmPersonMapper alarmPersonMapper;
    @Resource
    private DlbjViolationMapper dlbjViolationMapper;
    @Resource
    private ITlThresholdService tlThresholdService;

    @Override
    public List getTotalNum(JSONObject params) throws HssException {
        Map map = new HashMap();
        List result = elementTotalMapper.getTotalNum(map);
        return result;
    }

    @Override
    public JSONObject getNumByType(JSONObject params) throws HssException {
        JSONObject jsonObject = new JSONObject();
        List<Map> result = elementTotalMapper.getNumByType(params);
        Integer totalOnliNum = 0;
        Integer totalNum = 0;
        for (Map map : result) {
            totalOnliNum += Integer.parseInt(map.get("onlinum").toString());
            totalNum += Integer.parseInt(map.get("num").toString());
        }
        jsonObject.put("totalOnliNum", totalOnliNum);
        jsonObject.put("totalNum", totalNum);
        jsonObject.put("result", result);
        return jsonObject;
    }

    @Override
    public List getTrashCleanMap(JSONObject params) throws HssException {
        Map map = new HashMap();
        List result = elementTotalMapper.getTrashCleanMap(map);
        return result;
    }

    @Override
    public JSONObject getAddrForMapByType(JSONObject params) throws HssException {
        JSONObject json = new JSONObject();
        String depid = params.getString("depid");
        Map map = new HashMap();
        map.put("deptid", depid);
        List faclList = elementTotalMapper.getFaclAddrForMap(map);
        List carList = elementTotalMapper.getCarAddrForMap(map);
        List emplList = elementTotalMapper.getEmpAddrForMap(map);
        List parklList = elementTotalMapper.getParkDetailMap(map);
        List treelList = elementTotalMapper.getAciTreeDetailMap(map);
//        faclList.addAll(parklList);
//        faclList.addAll(treelList);
        QueryWrapper<Cases> casesQueryWrapper = new QueryWrapper<>();

        if (StringUtils.isNotEmpty(depid)) {
            casesQueryWrapper.lambda().eq(Cases::getDepid, depid);
        }
        Integer[] status = new Integer[]{1, 2, 3};
        casesQueryWrapper.lambda().in(Cases::getStatus, Arrays.asList(status));
        List caselist = casesService.list(casesQueryWrapper);
        json.put("faclList", faclList);
        json.put("carList", carList);
        json.put("emplList", emplList);
        json.put("caselist", caselist);
        json.put("parklList", parklList);
        json.put("treelList", treelList);

        return json;
    }

    @Override
    public JSONObject getAddrForMap(JSONObject params) throws HssException {
        JSONObject json = new JSONObject();
        String depid = params.getString("depid");
        Map map = new HashMap();
        map.put("deptid", depid);
        QueryWrapper<Cases> casesQueryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(depid)) {
            casesQueryWrapper.lambda().eq(Cases::getDepid, depid);
        }
        Integer[] status = new Integer[]{1, 2, 3};
        casesQueryWrapper.lambda().in(Cases::getStatus, Arrays.asList(status));
        List caselist = casesService.list(casesQueryWrapper);

        List<HomePageIconVo> videoFaclList = elementTotalMapper.getVideoFaclList();
        List<HomePageIconVo> employeeFaclList = elementTotalMapper.getEmployeeFaclList();
        Map<String, List<TlOperation>> tlOperationCollect = tlOperationMapper.selectList(new QueryWrapper<>()).stream().collect(Collectors.groupingBy(TlOperation::getId));
        List<HomePageIconVo> carFaclList = elementTotalMapper.getCarFaclList();
        for (HomePageIconVo homePageIconVo : carFaclList) {
            if (homePageIconVo.getSpeed() > 0) {
                homePageIconVo.setMove("0");
            } else {
                homePageIconVo.setMove("1");
            }
        }
        carFaclList.forEach(homePageIconVo -> {
            List<TlOperation> tlOperationList = tlOperationCollect.get(homePageIconVo.getCarcategory());
            if (null != tlOperationList) {
                List<TlOperation> jxqsCollect = tlOperationList.stream().filter(tlOperation -> null != tlOperation.getOperationtype() && (tlOperation.getOperationtype().equals("清扫作业") || tlOperation.getOperationtype().equals("洒水作业"))).collect(Collectors.toList());
                if (!jxqsCollect.isEmpty()) {
                    homePageIconVo.setJobType(2);
                }
                List<TlOperation> ljqyCollect = tlOperationList.stream().filter(tlOperation -> null != tlOperation.getOperationtype() && tlOperation.getOperationtype().equals("垃圾清运")).collect(Collectors.toList());
                if (!ljqyCollect.isEmpty()) {
                    homePageIconVo.setJobType(3);
                }
                List<TlOperation> ljzyCollect = tlOperationList.stream().filter(tlOperation -> null != tlOperation.getOperationtype() && tlOperation.getOperationtype().equals("垃圾转运")).collect(Collectors.toList());
                if (!ljzyCollect.isEmpty()) {
                    homePageIconVo.setJobType(4);
                }
            }
        });
        List<HomePageIconVo> treeFaclList = elementTotalMapper.getTreeFaclList();
        List<HomePageIconVo> parkFaclList = elementTotalMapper.getParkFaclList();
        List<HomePageIconVo> homePageIconVoList = new ArrayList<>();
        homePageIconVoList.addAll(videoFaclList);
        homePageIconVoList.addAll(employeeFaclList);
        homePageIconVoList.addAll(carFaclList);
        homePageIconVoList.addAll(treeFaclList);
        homePageIconVoList.addAll(parkFaclList);
        homePageIconVoList.forEach(homePageIconVo -> {
            if (null != homePageIconVo.getEquipid()) {
                QueryWrapper<TlChannel> tlChannelQueryWrapper = new QueryWrapper<>();
                tlChannelQueryWrapper.lambda().eq(TlChannel::getEquipid, homePageIconVo.getEquipid());
                tlChannelQueryWrapper.lambda().orderByAsc(TlChannel::getChannelname);
                List details = tlChannelMapper.selectList(tlChannelQueryWrapper);
                homePageIconVo.setDetails(details);
            }
        });
        json.put("list", homePageIconVoList);
        json.put("caselist", caselist);
        return json;
    }


    @Override
    public List getToiletNumMap(JSONObject params) throws HssException {
        Map map = new HashMap();
        List result = elementTotalMapper.getToiletNumMap(map);
        return result;
    }

    @Override
    public List getToiletDetailMap(JSONObject params) throws HssException {
        Map map = new HashMap();
        List result = elementTotalMapper.getToiletDetailMap(params);
        return result;
    }

    @Override
    public List getToiletStatusNumMap(JSONObject params) throws HssException {
        Map map = new HashMap();
        List result = elementTotalMapper.getToiletStatusNumMap(map);
        return result;
    }

    @Override
    public Map<String, Integer> getGreenAreaMap(JSONObject params) throws HssException {
        Map map = new HashMap();
        Map<String, Integer> result = elementTotalMapper.getGreenAreaMap(map);
        BigDecimal areaSum = MathUtils.getBigDecimal(result.get("areaSum"));
        BigDecimal greenarea = MathUtils.getBigDecimal(result.get("greenarea"));
        BigDecimal greeningRate = BigDecimal.ZERO;
        if (BigDecimal.ZERO != areaSum) {
            greeningRate = greenarea.divide(areaSum, 4, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100)).setScale(0, BigDecimal.ROUND_UP);
            result.put("greeningRate", greeningRate.intValue());
        }
        return result;
    }

    @Override
    public List getParkDetailMap(JSONObject params) throws HssException {
        Map map = new HashMap();
        List result = elementTotalMapper.getParkDetailMap(map);
        return result;
    }

    @Override
    public List getAciTreeDetailMap(JSONObject params) throws HssException {
        Map map = new HashMap();
        List result = elementTotalMapper.getAciTreeDetailMap(map);
        return result;
    }

    @Override
    public Map<String, Integer> getGreenStatusMap(JSONObject params) throws HssException {
        Map map = new HashMap();
        Map<String, Integer> result = elementTotalMapper.getGreenStatusMap(map);

        BigDecimal number = MathUtils.getBigDecimal(result.get("number"));
        BigDecimal growthsituation = MathUtils.getBigDecimal(result.get("growthsituation"));
        BigDecimal curingway = MathUtils.getBigDecimal(result.get("curingway"));

        if (BigDecimal.ZERO != number) {
            BigDecimal growthsituationRate = growthsituation.divide(number, 4, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100)).setScale(0, BigDecimal.ROUND_UP);
            result.put("growthsituationRate", growthsituationRate.intValue());

            BigDecimal curingwayRate = curingway.divide(number, 4, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100)).setScale(0, BigDecimal.ROUND_UP);
            result.put("curingwayRate", curingwayRate.intValue());
        }
        return result;
    }

    @Override
    public List getSensorStatusMap(JSONObject params) throws HssException {
        Map map = new HashMap();
        List result = elementTotalMapper.getSensorStatusMap(map);
        return result;
    }

    @Override
    public Map getVideoMap(JSONObject params) throws HssException {
        List<Map> result = new ArrayList<>();
        Map resmap = new LinkedHashMap();

        Map map = new HashMap();
        map.put("bindtypeitem", params.getString("bindtypeitem"));
        map.put("facType", params.getString("facType"));
        map.put("type", params.getString("type"));
        map.put("deptid", params.getString("deptid"));
        map.put("equipcode", params.getString("equipcode"));
        map.put("bindname", params.getString("bindname"));
        map.put("onlinestatus", params.getString("onlinestatus"));
        map.put("equipmodel", params.getString("equipmodel"));
        List<Map> vioList = elementTotalMapper.getVideoMap(map);
        List<Map> realVioList = new ArrayList<>();
        int number = 0;
        int total = 0;
        for (Map viomap : vioList) {
            Map paramap = new HashMap();
            paramap.put("equipid", viomap.get("id"));
            List details = tlChannelMapper.selectByMap(paramap);
            viomap.put("details", details);
            if (!CollectionUtils.isEmpty(details) && null != viomap.get("bindname")) {
                realVioList.add(viomap);
                total += details.size();
                if (viomap.get("onlinestatus").equals("0")) {
                    number += details.size();
                }
            }
        }
        resmap.put("onlinenum", number);
        resmap.put("totalnum", total);
        resmap.put("vioList", realVioList);
        result.add(resmap);
        return resmap;
    }

    @Override
    @DataScope(deptAlias = "binddeptid", userAlias = "createby, updateby")
    public JSONObject getVideoMapList(BaseEntity entity, JSONObject params) throws HssException {
        Long page = StringUtils.isEmpty(params.getLong("page")) ? 1 : params.getLong("page");
        Long size = StringUtils.isEmpty(params.getLong("size")) ? 10 : params.getLong("size");
        JSONObject json = new JSONObject();

        Map map = new HashMap();
        map.put("bindtypeitem", params.getString("bindtypeitem"));
        map.put("type", params.getString("type"));
        map.put("facType", params.getString("facType"));
        map.put("deptid", params.getString("deptid"));
        map.put("equipcode", params.getString("equipcode"));
        map.put("bindname", params.getString("bindname"));
        map.put("onlinestatus", params.getString("onlinestatus"));
        map.put("equipmodel", params.getString("equipmodel"));
        map.put("bindobjid", params.getString("bindobjid"));
        map.put("params", entity.getParams());
        Page<Map> listPage = new Page<>(page, size, true);
        IPage<Map> iPage = elementTotalMapper.getVideoMapList(listPage, map);
        for (Map viomap : iPage.getRecords()) {
            Map paramap = new HashMap();
            paramap.put("equipid", viomap.get("id"));
            List details = tlChannelMapper.selectByMap(paramap);
            viomap.put("details", details);
        }
        json.put("total", iPage.getTotal());
        json.put("size", iPage.getSize());
        json.put("pages", iPage.getPages());
        json.put("current", iPage.getCurrent());
        json.put("equiplist", iPage.getRecords());
        return json;
    }

    @Override
    public List getCarDetailByid(JSONObject params) throws HssException {
        Map map = new HashMap();
        map.put("carid", params.getString("carid"));
        List result = elementTotalMapper.getCarDetailByid(map);
        return result;
    }

    @Override
    public Map getFaclAlarmNum() throws HssException {

        String date = DateUtil.formatDate(new Date());
        Map map = new HashMap();
        if (StringUtils.isNotEmpty(date)) {
            String startDate = AttributeUtils.timeCompletion(date, 's');
            String endDate = AttributeUtils.timeCompletion(date, 'e');

            map.put("startDate", startDate);
            map.put("endDate", endDate);
        }

        Map result = elementTotalMapper.getFaclAlarmNum(map);
        return result;
    }

    @Override
    public List getCarLocation(JSONObject params) throws Exception {
        Map map = new HashMap();
        map.put("bindobjid", params.getString("bindobjid"));
        map.put("starttime", params.getString("starttime"));
        map.put("endtime", params.getString("endtime"));
//        List re = new ArrayList();
        List result = elementTotalMapper.getCarLocation(map);//轨迹

//        List<Grid> gridList = elementTotalMapper.getGridLocation();//当天的网格
//        for (KfkCarLocation car : result) {
//            Double lat = Double.valueOf(car.getLat());
//            Double lon = Double.valueOf(car.getLon());
//            for (Grid grid : gridList) {
//                Double lineWidth = grid.getLineWidth();
//                String lngLat = grid.getLnglat();
//                Boolean flag = DistanceUtils.insideLine(lon, lat, lngLat, lineWidth);
//                if (flag) {
//                    log.info("-------------");
//                }
//            }
//        }
        return result;
    }

    @Override
    public List getEmpLocation(JSONObject params) throws Exception {
        Map map = new HashMap();
        map.put("bindobjid", params.getString("bindobjid"));
        map.put("starttime", params.getString("starttime"));
        map.put("endtime", params.getString("endtime"));
        List result = elementTotalMapper.getEmpLocation(map);
        return result;
    }

    @Override
    public List getSearchList(EmpAndCarAndFaclTo empAndCarAndFaclTo) throws Exception {
        List resultList = new ArrayList();
        if (StringUtils.isNotEmpty(empAndCarAndFaclTo.getType())){
            String[] paramList = empAndCarAndFaclTo.getType().split(",");
            for (String typeParam : paramList) {
                if (typeParam.equals("车辆")) {
                    Map carMap = new HashMap();
                    carMap.put("title", "车辆");
                    empAndCarAndFaclTo.setType(typeParam);
                    List<CarSearchListVo> carSearchList = getCarSearchList(empAndCarAndFaclTo);
                    carMap.put("children", carSearchList);
                    resultList.add(carMap);
                } else if (typeParam.equals("人员")) {
                    Map empMap = new HashMap();
                    empMap.put("title", "人员");
                    empAndCarAndFaclTo.setType(typeParam);
                    List<EmpSearchListVo> empSearchList = getEmpSearchList(empAndCarAndFaclTo);
                    empMap.put("children", empSearchList);
                    resultList.add(empMap);
                } else {
                    Map empMap = new HashMap();
                    empMap.put("title", typeParam);
                    empAndCarAndFaclTo.setType(typeParam);
                    List<FaclSearchListVo> faclSearchList = elementTotalMapper.getFaclSearchList(empAndCarAndFaclTo);
                    Map<Object, List<TlChannel>> tlChannelCollect = tlChannelMapper.selectList(new QueryWrapper<>()).stream().filter(item -> StringUtils.isNotEmpty(item.getEquipid()))
                            .collect(Collectors.groupingBy(TlChannel::getEquipid));
                    faclSearchList.forEach(faclSearch -> {
                        faclSearch.setTlChannelList(tlChannelCollect.get(faclSearch.getEquipId()));
                    });
                    empMap.put("children", faclSearchList);
                    System.out.println(faclSearchList.size());
                    resultList.add(empMap);
                }
            }
        }

        return resultList;

    }

    @Override
    public List<EmpSearchListVo> getEmpSearchList(EmpAndCarAndFaclTo empAndCarAndFaclTo) {
        QueryWrapper<TlEmployee> tlEmployeeQueryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(empAndCarAndFaclTo.getAttendance())) {
            tlEmployeeQueryWrapper.lambda().eq(TlEmployee::getAttendance, empAndCarAndFaclTo.getAttendance());
            tlEmployeeQueryWrapper.lambda().orderByAsc(TlEmployee::getAttendance);
        }
        if (StringUtils.isNotEmpty(empAndCarAndFaclTo.getShiftStatus())) {
            tlEmployeeQueryWrapper.lambda().eq(TlEmployee::getShiftStatus, empAndCarAndFaclTo.getShiftStatus());
        }
        if (StringUtils.isNotEmpty(empAndCarAndFaclTo.getOnGuardStatus())) {
            tlEmployeeQueryWrapper.lambda().eq(TlEmployee::getOnguardstatus, empAndCarAndFaclTo.getOnGuardStatus());
        }
        if (StringUtils.isNotEmpty(empAndCarAndFaclTo.getName())) {
            tlEmployeeQueryWrapper.lambda().like(TlEmployee::getName, empAndCarAndFaclTo.getName());
        }
        List<TlEmployee> tlEmployeeList = tlEmployeeMapper.selectList(tlEmployeeQueryWrapper);

        QueryWrapper<TlEquip> tlEquipQueryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(empAndCarAndFaclTo.getOnlineStatus())) {
            tlEquipQueryWrapper.lambda().orderByAsc(TlEquip::getOnlinestatus);
        }
        List<TlEquip> tlEquipList = tlEquipMapper.selectList(tlEquipQueryWrapper);

        Map<String, List<TlEquip>> tlEquipCollect = tlEquipList.stream().filter(item -> StringUtils.isNotEmpty(item.getBindobjid())).collect(Collectors.groupingBy(TlEquip::getBindobjid));

        QueryWrapper<TlEquiptype> tlEquiptypeQueryWrapper = new QueryWrapper<>();
        List<TlEquiptype> tlEquiptypeList = tlEquiptypeMapper.selectList(tlEquiptypeQueryWrapper);

        Map<String, TlEquiptype> tlEquiptypeMap = tlEquiptypeList.stream().collect(Collectors.groupingBy(TlEquiptype::getId, Collectors.collectingAndThen(Collectors.toList(), tlEquiptypes -> tlEquiptypes.get(0))));

        QueryWrapper<TlChannel> tlChannelQueryWrapper = new QueryWrapper<>();
        tlChannelQueryWrapper.lambda().orderByAsc(TlChannel::getChannelname);
        Map<Object, List<TlChannel>> tlChannelCollect = tlChannelMapper.selectList(tlChannelQueryWrapper).stream().filter(item -> StringUtils.isNotEmpty(item.getEquipid()))
                .collect(Collectors.groupingBy(TlChannel::getEquipid));

        Map<String, TlWorkType> tlWorkTypeCollect = tlWorkTypeMapper.selectList(new QueryWrapper<>()).stream().collect(Collectors.groupingBy(TlWorkType::getId, Collectors.collectingAndThen(Collectors.toList(), tlWorkTypes -> tlWorkTypes.get(0))));

        Map<String, SysDepart> sysDepartCollect = sysDepartMapper.selectList(new QueryWrapper<>()).stream().collect(Collectors.groupingBy(SysDepart::getId, Collectors.collectingAndThen(Collectors.toList(), sysDeparts -> sysDeparts.get(0))));

        List<EmpSearchListVo> empSearchListVoList = new ArrayList<>();
        tlEmployeeList.forEach(tlEmployee -> {
            EmpSearchListVo empSearchListVo = new EmpSearchListVo();
            empSearchListVo.setType("人员");
            empSearchListVo.setShiftStatus(tlEmployee.getShiftStatus());
            empSearchListVo.setOnGuardStatus(tlEmployee.getOnguardstatus());
            empSearchListVo.setAttendance(tlEmployee.getAttendance());
            empSearchListVo.setPersonPhoto(tlEmployee.getPersonphoto());
            empSearchListVo.setId(tlEmployee.getId());
            empSearchListVo.setAddr(tlEmployee.getAddr());
            empSearchListVo.setOnlineStatus("2");
            empSearchListVo.setVideoOnlineStatus("2");
            List<TlEquip> tlEquips = tlEquipCollect.get(tlEmployee.getId());
            if (null != tlEquips) {

                List<TlEquip> locationOnlineList = tlEquips.stream().filter(tlEquip -> null != tlEquip.getEquiptypeid() && tlEquip.getEquiptypeid().equals("dc605bf7800b204e3015ac977542e66b")).collect(Collectors.toList());
                locationOnlineList.forEach(tlEquip -> {
                    if (StringUtils.isNotEmpty(tlEquip.getOnlinestatus())) {
                        empSearchListVo.setOnlineStatus(tlEquip.getOnlinestatus());
                    } else {
                        empSearchListVo.setOnlineStatus("2");
                    }
                });
                List<TlEquip> videoOnlineList = tlEquips.stream().filter(tlEquip -> null != tlEquip.getEquiptypeid() && tlEquip.getEquiptypeid().equals("10d4a7cced3e151606c42e7901757b0a")).collect(Collectors.toList());
                videoOnlineList.forEach(tlEquip -> {
                    empSearchListVo.setEquipId(tlEquip.getId());
                    empSearchListVo.setEquipCode(tlEquip.getEquipcode());
                    empSearchListVo.setBindtime(tlEquip.getBindtime());
                    empSearchListVo.setCreatetime(tlEquip.getCreatetime());
                    TlEquiptype tlEquiptype = tlEquiptypeMap.get(tlEquip.getEquiptypeid());
                    if (null != tlEquiptype) {
                        empSearchListVo.setEqpType(tlEquiptype.getEquipname());
                    }
                    if (StringUtils.isNotEmpty(tlEquip.getOnlinestatus())) {
                        empSearchListVo.setVideoOnlineStatus(tlEquip.getOnlinestatus());
                    } else {
                        empSearchListVo.setVideoOnlineStatus("2");
                    }
                    empSearchListVo.setTlChannelList(tlChannelCollect.get(tlEquip.getId()));
                });
            }
            TlWorkType tlWorkType = tlWorkTypeCollect.get(tlEmployee.getWorktype());
            if (null != tlWorkType) {
                empSearchListVo.setTypeName(tlWorkType.getWorktype());
                empSearchListVo.setName(tlEmployee.getName() + "[" + tlWorkType.getWorktype() + "]");
            }
            SysDepart sysDepart = sysDepartCollect.get(tlEmployee.getEmpldeptid());
            if (null != sysDepart) {
                empSearchListVo.setCompany(sysDepart.getDepartName());
            }
            empSearchListVoList.add(empSearchListVo);
        });

        List<EmpSearchListVo> empSelectList = new ArrayList<>();
        if (StringUtils.isNotEmpty(empAndCarAndFaclTo.getItemType()) && StringUtils.isNotEmpty(empAndCarAndFaclTo.getOnlineStatus())) {
            empSelectList = empSearchListVoList.stream().filter(empSearchListVo -> (null != empSearchListVo.getTypeName() && empSearchListVo.getTypeName().equals(empAndCarAndFaclTo.getItemType())) && (null != empSearchListVo.getOnlineStatus() && empSearchListVo.getOnlineStatus().equals(empAndCarAndFaclTo.getOnlineStatus()))).collect(Collectors.toList());
        } else if (StringUtils.isNotEmpty(empAndCarAndFaclTo.getItemType())) {
            empSelectList = empSearchListVoList.stream().filter(empSearchListVo -> (null != empSearchListVo.getTypeName() && empSearchListVo.getTypeName().equals(empAndCarAndFaclTo.getItemType()))).collect(Collectors.toList());
        } else if (StringUtils.isNotEmpty(empAndCarAndFaclTo.getOnlineStatus())) {
            empSelectList = empSearchListVoList.stream().filter(empSearchListVo -> (null != empSearchListVo.getOnlineStatus() && empSearchListVo.getOnlineStatus().equals(empAndCarAndFaclTo.getOnlineStatus()))).collect(Collectors.toList());
        } else if (StringUtils.isNotEmpty(empAndCarAndFaclTo.getCompany())) {
            empSelectList = empSearchListVoList.stream().filter(empSearchListVo -> (null != empSearchListVo.getCompany() && empSearchListVo.getCompany().equals(empAndCarAndFaclTo.getCompany()))).collect(Collectors.toList());
        } else {
            empSelectList = empSearchListVoList;
        }
        ListEmpSort(empSelectList);
        return empSelectList;
    }


    /**
     * 根据时间排序（其他排序如根据id排序也类似）
     *
     * @param empSearchListVoList
     */
    private static void ListEmpSort(List<EmpSearchListVo> empSearchListVoList) {
        //用Collections这个工具类传list进来排序
        Collections.sort(empSearchListVoList, new Comparator<EmpSearchListVo>() {
            @Override
            public int compare(EmpSearchListVo o1, EmpSearchListVo o2) {
                int online1 = Objects.isNull(o1.getOnlineStatus()) ? 2 : Integer.parseInt(o1.getOnlineStatus());
                int online2 = Objects.isNull(o2.getOnlineStatus()) ? 2 : Integer.parseInt(o2.getOnlineStatus());
                Date createtime1 = Objects.isNull(o1.getCreatetime()) ? new Date( Long.MAX_VALUE ) : o1.getCreatetime();
                Date createtime2 = Objects.isNull(o2.getCreatetime()) ? new Date( Long.MAX_VALUE ) : o2.getCreatetime();
                int attendance1 = Objects.isNull(o1.getAttendance()) ? 1 : o1.getAttendance();
                int attendance2 = Objects.isNull(o2.getAttendance()) ? 1 : o2.getAttendance();
                int onguard1 = Objects.isNull(o1.getOnGuardStatus()) ? 1 : o1.getOnGuardStatus();
                int onguard2 = Objects.isNull(o2.getOnGuardStatus()) ? 1 : o2.getOnGuardStatus();


                if (online1>online2) {
                    return 1;//-1是排在前
                }else if (online1<online2) {
                    return -1;//1是排在后
                }else {
                    if(attendance1>attendance2){
                        return 1;
                    }else if(attendance1<attendance2){
                        return -1;
                    }else{
                        if(onguard1>onguard2){
                            return 1;
                        }else if(onguard1<onguard2){
                            return -1;
                        }else{
                            if (createtime1.compareTo(createtime2) < 0) {
                                return -1;
                            }else if (createtime1.compareTo(createtime2) > 0) {
                                return 1;
                            }else {
                                return 0;
                            }
                        }
                    }
                }
            }
        });
    }


    @Override
    public List<CarSearchListVo> getCarSearchList(EmpAndCarAndFaclTo empAndCarAndFaclTo) {
        QueryWrapper<TlCar> tlCarQueryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(empAndCarAndFaclTo.getAttendance())) {
            tlCarQueryWrapper.lambda().eq(TlCar::getAttendance, empAndCarAndFaclTo.getAttendance());
        }
        if (StringUtils.isNotEmpty(empAndCarAndFaclTo.getShiftStatus())) {
            tlCarQueryWrapper.lambda().eq(TlCar::getShiftStatus, empAndCarAndFaclTo.getShiftStatus());
        }
        if (StringUtils.isNotEmpty(empAndCarAndFaclTo.getOnGuardStatus())) {
            tlCarQueryWrapper.lambda().eq(TlCar::getOnguardstatus, empAndCarAndFaclTo.getOnGuardStatus());
        }
        if (StringUtils.isNotEmpty(empAndCarAndFaclTo.getName())) {
            tlCarQueryWrapper.lambda().like(TlCar::getCarnumber, empAndCarAndFaclTo.getName());
        }
        List<TlCar> tlCarList = tlCarMapper.selectList(tlCarQueryWrapper);

        QueryWrapper<TlEquip> tlEquipQueryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(empAndCarAndFaclTo.getOnlineStatus())) {
        }
        List<TlEquip> tlEquipList = tlEquipMapper.selectList(tlEquipQueryWrapper);

        Map<String, List<TlEquip>> tlEquipCollect = tlEquipList.stream().filter(item -> StringUtils.isNotEmpty(item.getBindobjid())).collect(Collectors.groupingBy(TlEquip::getBindobjid));
        QueryWrapper<TlEquiptype> tlEquiptypeQueryWrapper = new QueryWrapper<>();
        List<TlEquiptype> tlEquiptypeList = tlEquiptypeMapper.selectList(tlEquiptypeQueryWrapper);

        Map<String, TlEquiptype> tlEquiptypeMap = tlEquiptypeList.stream().collect(Collectors.groupingBy(TlEquiptype::getId, Collectors.collectingAndThen(Collectors.toList(), tlEquiptypes -> tlEquiptypes.get(0))));

        QueryWrapper<TlCarType> tlCarTypeQueryWrapper = new QueryWrapper<>();
        Map<String, TlCarType> tlCarTypeCollect = tlCarTypeMapper.selectList(tlCarTypeQueryWrapper).stream().collect(Collectors.groupingBy(TlCarType::getId, Collectors.collectingAndThen(Collectors.toList(), tlCarTypes -> tlCarTypes.get(0))));


        Map<String, List<TlOperation>> tlOperationCollect = tlOperationMapper.selectList(new QueryWrapper<>()).stream().collect(Collectors.groupingBy(TlOperation::getId));
        QueryWrapper<TlChannel> tlChannelQueryWrapper = new QueryWrapper<>();
        tlChannelQueryWrapper.lambda().orderByAsc(TlChannel::getChannelname);
        Map<Object, List<TlChannel>> tlChannelCollect = tlChannelMapper.selectList(tlChannelQueryWrapper).stream().filter(item -> StringUtils.isNotEmpty(item.getEquipid()))
                .collect(Collectors.groupingBy(TlChannel::getEquipid));

        Map<String, SysDepart> sysDepartCollect = sysDepartMapper.selectList(new QueryWrapper<>()).stream().collect(Collectors.groupingBy(SysDepart::getId, Collectors.collectingAndThen(Collectors.toList(), sysDeparts -> sysDeparts.get(0))));

        List<CarSearchListVo> carSearchListVoList = new ArrayList<>();
        tlCarList.forEach(tlCar -> {
            CarSearchListVo carSearchListVo = new CarSearchListVo();
            carSearchListVo.setType("车辆");
            carSearchListVo.setShiftStatus(tlCar.getShiftStatus());
            carSearchListVo.setOnGuardStatus(tlCar.getOnguardstatus());
            carSearchListVo.setAttendance(tlCar.getAttendance());
            carSearchListVo.setSpeed((null == tlCar.getSpeed() ? 0 : tlCar.getSpeed()));
            carSearchListVo.setCarPicture(tlCar.getCarpicture());
            carSearchListVo.setId(tlCar.getId());
            carSearchListVo.setAddr(tlCar.getAddr());
            carSearchListVo.setOnlineStatus("2");
            carSearchListVo.setVideoOnlineStatus("2");
            //获取视频设备在线情况 和 定位油感在线情况
            List<TlEquip> tlEquips = tlEquipCollect.get(tlCar.getId());
            if (null != tlEquips) {
                List<TlEquip> locationOnlineList = tlEquips.stream().filter(tlEquip -> null != tlEquip.getEquiptypeid() && tlEquip.getEquiptypeid().equals("252b781c1a454e042fe6531950f80b12")).collect(Collectors.toList());
                locationOnlineList.forEach(tlEquip -> {
                    if (StringUtils.isNotEmpty(tlEquip.getOnlinestatus())) {
                        carSearchListVo.setOnlineStatus(tlEquip.getOnlinestatus());
                    }
                });
                List<TlEquip> videoOnlineList = tlEquips.stream().filter(tlEquip -> null != tlEquip.getEquiptypeid() && tlEquip.getEquiptypeid().equals("e2f7d565202c5fc5c54b5d53073f0b1a")).collect(Collectors.toList());
                videoOnlineList.forEach(tlEquip -> {
                    carSearchListVo.setEquipId(tlEquip.getId());
                    carSearchListVo.setEquipCode(tlEquip.getEquipcode());
                    carSearchListVo.setBindtime(tlEquip.getBindtime());
                    carSearchListVo.setCreatetime(tlEquip.getCreatetime());
                    TlEquiptype tlEquiptype = tlEquiptypeMap.get(tlEquip.getEquiptypeid());
                    if (null != tlEquiptype) {
                        carSearchListVo.setEqpType(tlEquiptype.getEquipname());
                    }
                    if (StringUtils.isNotEmpty(tlEquip.getOnlinestatus())) {
                        carSearchListVo.setVideoOnlineStatus(tlEquip.getOnlinestatus());
                    }
                    carSearchListVo.setTlChannelList(tlChannelCollect.get(tlEquip.getId()));
                });
            }
            TlCarType tlCarType = tlCarTypeCollect.get(tlCar.getCartypeid());
            if (null != tlCarType) {
                carSearchListVo.setTypeName(tlCarType.getTypename());
                carSearchListVo.setName(tlCar.getCarnumber() + "[" + tlCarType.getTypename() + "]");
            }
            SysDepart sysDepart = sysDepartCollect.get(tlCar.getCardeptid());
            if (null != sysDepart) {
                carSearchListVo.setCompany(sysDepart.getDepartName());
            }
            List<TlOperation> tlOperationList = tlOperationCollect.get(tlCar.getCarcategory());
            if (null != tlOperationList) {
                List<TlOperation> jxqsCollect = tlOperationList.stream().filter(tlOperation -> null != tlOperation.getOperationtype() && (tlOperation.getOperationtype().equals("清扫作业") || tlOperation.getOperationtype().equals("洒水作业"))).collect(Collectors.toList());
                if (!jxqsCollect.isEmpty()) {
                    carSearchListVo.setJobType(2);
                }
                List<TlOperation> ljqyCollect = tlOperationList.stream().filter(tlOperation -> null != tlOperation.getOperationtype() && tlOperation.getOperationtype().equals("垃圾清运")).collect(Collectors.toList());
                if (!ljqyCollect.isEmpty()) {
                    carSearchListVo.setJobType(3);
                }
                List<TlOperation> ljzyCollect = tlOperationList.stream().filter(tlOperation -> null != tlOperation.getOperationtype() && tlOperation.getOperationtype().equals("垃圾转运")).collect(Collectors.toList());
                if (!ljzyCollect.isEmpty()) {
                    carSearchListVo.setJobType(4);
                }
            }
            carSearchListVoList.add(carSearchListVo);
        });
        List<CarSearchListVo> carSelectList = new ArrayList<>();
        if (StringUtils.isNotEmpty(empAndCarAndFaclTo.getItemType())) {
            if (StringUtils.isNotEmpty(empAndCarAndFaclTo.getOnlineStatus())) {
                carSelectList = carSearchListVoList.stream().filter(carSearchListVo -> (null != carSearchListVo.getTypeName() && carSearchListVo.getTypeName().equals(empAndCarAndFaclTo.getItemType())) && (null != carSearchListVo.getOnlineStatus() && carSearchListVo.getOnlineStatus().equals(empAndCarAndFaclTo.getOnlineStatus()))).collect(Collectors.toList());
            } else {
                carSelectList = carSearchListVoList.stream().filter(carSearchListVo -> (null != carSearchListVo.getTypeName() && carSearchListVo.getTypeName().equals(empAndCarAndFaclTo.getItemType()))).collect(Collectors.toList());
            }
        } else if (StringUtils.isNotEmpty(empAndCarAndFaclTo.getOnlineStatus())) {
            carSelectList = carSearchListVoList.stream().filter(carSearchListVo -> (null != carSearchListVo.getOnlineStatus() && carSearchListVo.getOnlineStatus().equals(empAndCarAndFaclTo.getOnlineStatus()))).collect(Collectors.toList());
        } else if (StringUtils.isNotEmpty(empAndCarAndFaclTo.getCompany())) {
            carSelectList = carSearchListVoList.stream().filter(carSearchListVo -> (null != carSearchListVo.getCompany() && carSearchListVo.getCompany().equals(empAndCarAndFaclTo.getCompany()))).collect(Collectors.toList());
        } else {
            carSelectList = carSearchListVoList;
        }
        ListCarSort(carSelectList);
        return carSelectList;
    }

    /**
     * 根据时间排序（其他排序如根据id排序也类似）
     *
     * @param carSearchListVoList
     */
    private static void ListCarSort(List<CarSearchListVo> carSearchListVoList) {
        //用Collections这个工具类传list进来排序
        Collections.sort(carSearchListVoList, new Comparator<CarSearchListVo>() {
            @Override
            public int compare(CarSearchListVo o1, CarSearchListVo o2) {
                int online1 = Objects.isNull(o1.getOnlineStatus()) ? 2 : Integer.parseInt(o1.getOnlineStatus());
                int online2 = Objects.isNull(o2.getOnlineStatus()) ? 2 : Integer.parseInt(o2.getOnlineStatus());
                Date bindtime1 = Objects.isNull(o1.getBindtime()) ? new Date( Long.MIN_VALUE ) : o1.getBindtime();
                Date bindtime2 = Objects.isNull(o2.getBindtime()) ? new Date( Long.MIN_VALUE ) : o2.getBindtime();
                int attendance1 = Objects.isNull(o1.getAttendance()) ? 1 : o1.getAttendance();
                int attendance2 = Objects.isNull(o2.getAttendance()) ? 1 : o2.getAttendance();
                int onguard1 = Objects.isNull(o1.getOnGuardStatus()) ? 1 : o1.getOnGuardStatus();
                int onguard2 = Objects.isNull(o2.getOnGuardStatus()) ? 1 : o2.getOnGuardStatus();

                if (online1>online2) {
                    return 1;//-1是排在后面
                }else if (online1<online2) {
                    return -1;//1是排在前面
                }else {
                    if(attendance1>attendance2){
                        return 1;
                    }else if(attendance1<attendance2){
                        return -1;
                    }else{
                        if(onguard1>onguard2){
                            return 1;
                        }else if(onguard1<onguard2){
                            return -1;
                        }else{
                            if (bindtime1.compareTo(bindtime2) < 0) {
                                return -1;
                            }else if (bindtime1.compareTo(bindtime2) > 0) {
                                return 1;
                            }else {
                                return 0;
                            }
                        }
                    }
                }
            }
        });
    }


    @Override
    public List<FaclSearchListVo> getFaclSearchList(EmpAndCarAndFaclTo empAndCarAndFaclTo) {
        Map map = new HashMap();
        List<FaclSearchListVo> faclSearchList = elementTotalMapper.getFaclSearchList(empAndCarAndFaclTo);
        QueryWrapper<TlChannel> tlChannelQueryWrapper = new QueryWrapper<>();
        tlChannelQueryWrapper.lambda().orderByAsc(TlChannel::getChannelname);
        Map<Object, List<TlChannel>> tlChannelCollect = tlChannelMapper.selectList(tlChannelQueryWrapper).stream().filter(item -> StringUtils.isNotEmpty(item.getEquipid()))
                .collect(Collectors.groupingBy(TlChannel::getEquipid));
        faclSearchList.forEach(faclSearch -> {
            faclSearch.setTlChannelList(tlChannelCollect.get(faclSearch.getEquipId()));
        });
        return faclSearchList;
    }

    @Override
    public Map getHummanTotal(JSONObject params) {
        Map map = new HashMap();
        map.put("faclid", params.getString("faclid"));
        Map result = elementTotalMapper.getHummanTotal(map);
        return result;
    }

    @Override
    public List<DTUDataMap> getDtuByFaclId(String facId) throws ProgramTerminationException {
        QueryWrapper<TlEquip> equipQueryWrapper = new QueryWrapper<>();
//        equipQueryWrapper.lambda().eq(TlEquip::getOnlinestatus, 0);
        equipQueryWrapper.lambda().eq(TlEquip::getBindobjid, facId);
        List<TlEquip> equipList = tlEquipMapper.selectList(equipQueryWrapper);
        if (equipList.isEmpty()) {
            throw new ProgramTerminationException("暂无设备");
        }
        Map<String, TlEquip> equipMap = GroupingByUtils.getGroupingForMapEntity(equipList, TlEquip::getEquipcode, Collectors.collectingAndThen(Collectors.toList(), value -> value.get(0)));
        QueryWrapper<KfkDtu> kfkDtuQueryWrapper = new QueryWrapper<>();
        kfkDtuQueryWrapper.lambda().in(KfkDtu::getEqpnum, equipMap.keySet());
        kfkDtuQueryWrapper.lambda().le(KfkDtu::getTimestamp, new Date());
        kfkDtuQueryWrapper.lambda().ge(KfkDtu::getTimestamp, new Date(Tools.getDateAddNumber(new Date(), -5)));
        kfkDtuQueryWrapper.lambda().orderByDesc(KfkDtu::getTimestamp);
        List<KfkDtu> kfkDtuList = kfkDtuMapper.selectList(kfkDtuQueryWrapper);
        if (kfkDtuList.isEmpty()) {
            throw new ProgramTerminationException("暂无设备");
        }
        Map<String, List<KfkDtu>> kfkDtuMap = GroupingByUtils.getGroupingForMapList(kfkDtuList, KfkDtu::getCategory);
        List<DTUDataMap> dtuDataMapList = new ArrayList<>();
        DTUDataMap dtuDataMap = null;
        List<TlThreshold> tlThresholdList = SpringUtils.getBean(TlThresholdMapper.class).selectList(
                new QueryWrapper<TlThreshold>().lambda().in(TlThreshold::getSysname,Arrays.stream(DTUEnum.values()).map(DTUEnum::getSysAlarmName).collect(Collectors.toList())));
        Map<String,TlThreshold> tlThresholdMap = GroupingByUtils.getGroupingForMapEntity(tlThresholdList,TlThreshold::getSysname
        ,Collectors.collectingAndThen(Collectors.toList(), value -> value.get(0)));
        for (DTUEnum dtuEnum : DTUEnum.values()) {
            if (!kfkDtuMap.containsKey(dtuEnum.getName())) {
                dtuDataMap = new DTUDataMap(dtuEnum.getName(), dtuEnum.getNotes(), null, 404, "暂无设备",null);
            } else {
                BigDecimal num = new BigDecimal(kfkDtuMap.get(dtuEnum.getName()).get(0).getValue().replaceAll("ppm", "").replaceAll("%RH", ""));
                BigDecimal flagNum = new BigDecimal(JSONObject.parseObject(tlThresholdMap.get(dtuEnum.getSysAlarmName()).getThreshold()).getString(dtuEnum.getFlag()));
                if(num.compareTo(flagNum)>=0){
                    dtuDataMap = new DTUDataMap(dtuEnum.getName(), dtuEnum.getNotes(),num.toString()+" ppm"
                            , 200, "设备正常", (short) 2);
                }else{
                    dtuDataMap = new DTUDataMap(dtuEnum.getName(), dtuEnum.getNotes(),num.toString()+" ppm"
                            , 200, "设备正常", (short) 1);
                }

            }
            dtuDataMapList.add(dtuDataMap);
        }
        return dtuDataMapList;
    }


    @Override
    public List<Map> getManholeCoverByFaclId(String facId) throws ProgramTerminationException {

        QueryWrapper<TlEquip> equipQueryWrapper = new QueryWrapper<>();
//        equipQueryWrapper.lambda().eq(TlEquip::getOnlinestatus, 0);
        equipQueryWrapper.lambda().eq(TlEquip::getBindobjid, facId);
        equipQueryWrapper.lambda().last(" limit 1");
        TlEquip equip = tlEquipMapper.selectOne(equipQueryWrapper);
        if (Objects.isNull(equip)) {
            throw new ProgramTerminationException("暂无设备");
        }

        QueryWrapper<KfkManholeCover> kfkDtuQueryWrapper = new QueryWrapper<>();
        kfkDtuQueryWrapper.lambda().in(KfkManholeCover::getEqpnum, equip.getEquipcode());
        kfkDtuQueryWrapper.lambda().le(KfkManholeCover::getTime, new Date());
        kfkDtuQueryWrapper.lambda().ge(KfkManholeCover::getTime, new Date(Tools.getDateAddNumber(new Date(), -5000)));
        kfkDtuQueryWrapper.lambda().orderByDesc(KfkManholeCover::getTime);
        kfkDtuQueryWrapper.lambda().last(" limit 1");
        KfkManholeCover kfkDtu = kfkManholeCoverMapper.selectOne(kfkDtuQueryWrapper);
        if (Objects.isNull(kfkDtu)) {
            throw new ProgramTerminationException("暂无设备记录");
        }

        List<Map> dataMapList = new ArrayList<>();

        Map<String, List<TlThreshold>> thresholdListMap = tlThresholdService.getThresholdListMap();
        List<TlThreshold> tlThresholds = thresholdListMap.get(facId);

        tlThresholds.forEach(t->{
            Map map = new HashMap();
            if ("开盖报警".equals(t.getSysname())){
                map.put("name", "manholeCover");
                map.put("notes", "井盖");
                if (1 == kfkDtu.getIsCoverAbnormal()){
                    map.put("value", "开盖");
                    map.put("flag", (short) 2);
                } else {
                    map.put("value", "正常");
                    map.put("flag", (short) 1);
                }
            }
            if ("水位超限".equals(t.getSysname())){
                map.put("name", "waterLevel");
                map.put("notes", "水位");
                if (1 == kfkDtu.getIsWaterAbnormal()){
                    map.put("value", "超限");
                    map.put("flag", (short) 2);
                } else {
                    map.put("value", "正常");
                    map.put("flag", (short) 1);
                }
            }
            dataMapList.add(map);
        });

        return dataMapList;
    }

    @Override
    public List<Map<String, Object>> getCarMoveStay(JSONObject params) {
        Map map = new HashMap();
        map.put("bindobjid", params.getString("bindobjid"));
        map.put("starttime", params.getString("starttime"));
        map.put("endtime", params.getString("endtime"));
        map.put("isstay", params.getString("isstay"));
        List<Map<String, Object>> results = elementTotalMapper.getCarMoveStay(map);
        for (Map<String, Object> result : results) {
            result.put("totalTime", StringUtils.isNotEmpty(result.get("second")) ? StringUtils.s2date(Long.parseLong(result.get("second").toString())) : "");
        }
        return results;
    }

    @Override
    public List getPersonMoveStay(JSONObject params) {
        Map map = new HashMap();
        map.put("bindobjid", params.getString("bindobjid"));
        map.put("starttime", params.getString("starttime"));
        map.put("isstay", params.getString("isstay"));
        map.put("endtime", params.getString("endtime"));
        List result = elementTotalMapper.getPersonMoveStay(map);
        return result;
    }

    @Override
    public JSONObject getTrashTree(JSONObject params) {
        JSONObject dataJson = new JSONObject();

        List<Object> towList = new ArrayList<>();

        JSONObject contentJson = new JSONObject();
        String ids = params.getString("id");
        String[] id = ids.split(",");
        List<String> idList = Arrays.asList(id);
        QueryWrapper<TlFacilitiesType> tlFacilitiesTypeQueryWrapper = new QueryWrapper<>();
        tlFacilitiesTypeQueryWrapper.lambda().in(TlFacilitiesType::getId, idList);
        List<TlFacilitiesType> tlFacilitiesTypeList = iTlFacilitiesTypeService.list(tlFacilitiesTypeQueryWrapper);
        for (TlFacilitiesType tlFacilitiesType : tlFacilitiesTypeList) {
            QueryWrapper<TlFacilitiesTypeItems> tlFacilitiesTypeItemsQueryWrapper = new QueryWrapper<>();
            tlFacilitiesTypeItemsQueryWrapper.lambda().eq(TlFacilitiesTypeItems::getFacilitietypeid, tlFacilitiesType.getId());
            List<TlFacilitiesTypeItems> tlFacilitiesTypeItemsList = iTlFacilitiesTypeItemsService.list(tlFacilitiesTypeItemsQueryWrapper);
            for (TlFacilitiesTypeItems tlFacilitiesTypeItems : tlFacilitiesTypeItemsList) {
                Map<String, Object> map = new HashMap<>();

                List<Map<String, Object>> treeList = new ArrayList<>();
                map.put("name", tlFacilitiesTypeItems.getItemtypename());
                map.put("type", "smallFacl");
                QueryWrapper<TlFacilities> tlFacilitiesQueryWrapper = new QueryWrapper<>();
                tlFacilitiesQueryWrapper.lambda().eq(TlFacilities::getFacltypeitemid, tlFacilitiesTypeItems.getId());
                List<TlFacilities> tlFacilitiesList = iTlFacilitiesService.list(tlFacilitiesQueryWrapper);
                Map<String, Object> threeMap;
                for (TlFacilities tlFacilities : tlFacilitiesList) {

                    threeMap = new HashMap<>();
                    threeMap.put("id", tlFacilities.getId());
                    threeMap.put("name", tlFacilities.getFaclname());
                    threeMap.put("type", "facl");
                    treeList.add(threeMap);
                }
                map.put("children", treeList);
                towList.add(map);
            }
        }
        contentJson.put("list", towList);
        dataJson.put("content", contentJson);
        return dataJson;
    }

    @Override
    public WorkTypeNumberVo getWorkTypeNumber(JSONObject params) throws HssException {
        WorkTypeNumberVo workTypeNumberVo = new WorkTypeNumberVo();
        List<EmployeeAndWorkTypeVo> employeeAndWorkTypeList = elementTotalMapper.getEmployeeAndWorkType();
        //公厕管理员
        List<EmployeeAndWorkTypeVo> publicToiletsList = employeeAndWorkTypeList.stream().filter(employeeAndWorkTypeVo -> null != employeeAndWorkTypeVo.getWorkType() && employeeAndWorkTypeVo.getWorkType().equals("公厕管理员")).collect(Collectors.toList());
        //填埋工
        List<EmployeeAndWorkTypeVo> landfillWorkList = employeeAndWorkTypeList.stream().filter(employeeAndWorkTypeVo -> null != employeeAndWorkTypeVo.getWorkType() && employeeAndWorkTypeVo.getWorkType().equals("填埋工")).collect(Collectors.toList());
        //收运工
        List<EmployeeAndWorkTypeVo> collectorWorkList = employeeAndWorkTypeList.stream().filter(employeeAndWorkTypeVo -> null != employeeAndWorkTypeVo.getWorkType() && employeeAndWorkTypeVo.getWorkType().equals("收运工")).collect(Collectors.toList());
        //清运工
        List<EmployeeAndWorkTypeVo> keepUpWorkList = employeeAndWorkTypeList.stream().filter(employeeAndWorkTypeVo -> null != employeeAndWorkTypeVo.getWorkType() && employeeAndWorkTypeVo.getWorkType().equals("清运工")).collect(Collectors.toList());
        //转运工
        List<EmployeeAndWorkTypeVo> transitWorkersList = employeeAndWorkTypeList.stream().filter(employeeAndWorkTypeVo -> null != employeeAndWorkTypeVo.getWorkType() && employeeAndWorkTypeVo.getWorkType().equals("转运工")).collect(Collectors.toList());
        //转运站管理员
        List<EmployeeAndWorkTypeVo> transferStationList = employeeAndWorkTypeList.stream().filter(employeeAndWorkTypeVo -> null != employeeAndWorkTypeVo.getWorkType() && employeeAndWorkTypeVo.getWorkType().equals("转运站管理员")).collect(Collectors.toList());
        //处理员
        Integer processorNumber = publicToiletsList.size() + landfillWorkList.size() + collectorWorkList.size() + keepUpWorkList.size() + transitWorkersList.size() + transferStationList.size();
        workTypeNumberVo.setProcessorNumber(processorNumber);

        List<TlEquip> tlEquipList = tlEquipService.list();
        Map<Object, List<TlEquip>> tlEquipCollect = tlEquipList.stream().filter(item -> StringUtils.isNotEmpty(item.getBindobjid())).collect(Collectors.groupingBy(TlEquip::getBindobjid));
        //公厕管理员在线离线数
        Integer publicToiletsOnlineNumber = 0;
        Integer publicToiletsOfflineNumber = 0;
        for (EmployeeAndWorkTypeVo employeeAndWorkTypeVo : publicToiletsList) {
            List<TlEquip> tlEquips = tlEquipCollect.get(employeeAndWorkTypeVo.getEmployeeId());
            if (null != tlEquips) {
                publicToiletsOnlineNumber += (int) tlEquips.stream().filter(tlEquip -> null != tlEquip.getOnlinestatus() && tlEquip.getOnlinestatus().equals("0")).count();
                publicToiletsOfflineNumber += (int) tlEquips.stream().filter(tlEquip -> null != tlEquip.getOnlinestatus() && tlEquip.getOnlinestatus().equals("1")).count();
            }
        }
        workTypeNumberVo.setPublicToiletsOnlineNumber(publicToiletsOnlineNumber);
        workTypeNumberVo.setPublicToiletsTotalNumber(publicToiletsList.size());
        //填埋工线离线数
        Integer landfillWorkOnlineNumber = 0;
        Integer landfillWorkOfflineNumber = 0;
        for (EmployeeAndWorkTypeVo employeeAndWorkTypeVo : landfillWorkList) {
            List<TlEquip> tlEquips = tlEquipCollect.get(employeeAndWorkTypeVo.getEmployeeId());
            if (null != tlEquips) {
                landfillWorkOnlineNumber += (int) tlEquips.stream().filter(tlEquip -> null != tlEquip.getOnlinestatus() && tlEquip.getOnlinestatus().equals("0")).count();
                landfillWorkOfflineNumber += (int) tlEquips.stream().filter(tlEquip -> null != tlEquip.getOnlinestatus() && tlEquip.getOnlinestatus().equals("1")).count();
            }
        }
        workTypeNumberVo.setLandfillWorkOnlineNumber(landfillWorkOnlineNumber);
        workTypeNumberVo.setLandfillWorkTotalNumber(landfillWorkList.size());
        //收运工线离线数
        Integer collectorWorkOnlineNumber = 0;
        Integer collectorWorkOfflineNumber = 0;
        for (EmployeeAndWorkTypeVo employeeAndWorkTypeVo : collectorWorkList) {
            List<TlEquip> tlEquips = tlEquipCollect.get(employeeAndWorkTypeVo.getEmployeeId());
            if (null != tlEquips) {
                collectorWorkOnlineNumber += (int) tlEquips.stream().filter(tlEquip -> null != tlEquip.getOnlinestatus() && tlEquip.getOnlinestatus().equals("0")).count();
                collectorWorkOfflineNumber += (int) tlEquips.stream().filter(tlEquip -> null != tlEquip.getOnlinestatus() && tlEquip.getOnlinestatus().equals("1")).count();
            }
        }
        workTypeNumberVo.setCollectorWorkOnlineNumber(collectorWorkOnlineNumber);
        workTypeNumberVo.setCollectorWorkTotalNumber(collectorWorkList.size());
        //清运工线离线数
        Integer keepUpWorkOnlineNumber = 0;
        Integer keepUpWorkOfflineNumber = 0;
        for (EmployeeAndWorkTypeVo employeeAndWorkTypeVo : keepUpWorkList) {
            List<TlEquip> tlEquips = tlEquipCollect.get(employeeAndWorkTypeVo.getEmployeeId());
            if (null != tlEquips) {
                keepUpWorkOnlineNumber += (int) tlEquips.stream().filter(tlEquip -> null != tlEquip.getOnlinestatus() && tlEquip.getOnlinestatus().equals("0")).count();
                keepUpWorkOfflineNumber += (int) tlEquips.stream().filter(tlEquip -> null != tlEquip.getOnlinestatus() && tlEquip.getOnlinestatus().equals("1")).count();
            }
        }
        workTypeNumberVo.setKeepUpWorkOnlineNumber(keepUpWorkOnlineNumber);
        workTypeNumberVo.setKeepUpWorkTotalNumber(keepUpWorkList.size());
        //转运工线离线数
        Integer transitWorkersOnlineNumber = 0;
        Integer transitWorkersOfflineNumber = 0;
        for (EmployeeAndWorkTypeVo employeeAndWorkTypeVo : transitWorkersList) {
            List<TlEquip> tlEquips = tlEquipCollect.get(employeeAndWorkTypeVo.getEmployeeId());
            if (null != tlEquips) {
                transitWorkersOnlineNumber += (int) tlEquips.stream().filter(tlEquip -> null != tlEquip.getOnlinestatus() && tlEquip.getOnlinestatus().equals("0")).count();
                transitWorkersOfflineNumber += (int) tlEquips.stream().filter(tlEquip -> null != tlEquip.getOnlinestatus() && tlEquip.getOnlinestatus().equals("1")).count();
            }
        }
        workTypeNumberVo.setTransitWorkersOnlineNumber(transitWorkersOnlineNumber);
        workTypeNumberVo.setTransitWorkersTotalNumber(transitWorkersList.size());
        //转运站管理员线离线数
        Integer transferStationOnlineNumber = 0;
        Integer transferStationOfflineNumber = 0;
        for (EmployeeAndWorkTypeVo employeeAndWorkTypeVo : transferStationList) {
            List<TlEquip> tlEquips = tlEquipCollect.get(employeeAndWorkTypeVo.getEmployeeId());
            if (null != tlEquips) {
                transferStationOnlineNumber += (int) tlEquips.stream().filter(tlEquip -> null != tlEquip.getOnlinestatus() && tlEquip.getOnlinestatus().equals("0")).count();
                transferStationOfflineNumber += (int) tlEquips.stream().filter(tlEquip -> null != tlEquip.getOnlinestatus() && tlEquip.getOnlinestatus().equals("1")).count();
            }
        }
        workTypeNumberVo.setTransferStationOnlineNumber(transferStationOnlineNumber);
        workTypeNumberVo.setTransferStationTotalNumber(transferStationList.size());
        //处理员在线数离线数
        Integer processorOnlineNumber = publicToiletsOnlineNumber + landfillWorkOnlineNumber + collectorWorkOnlineNumber + keepUpWorkOnlineNumber + transitWorkersOnlineNumber + transferStationOnlineNumber;
        Integer processorOfflineNumber = publicToiletsOfflineNumber + landfillWorkOfflineNumber + collectorWorkOfflineNumber + keepUpWorkOfflineNumber + transitWorkersOfflineNumber + transferStationOfflineNumber;
        Integer processorNoDeviceNumber = processorNumber - processorOnlineNumber - processorOfflineNumber;
        workTypeNumberVo.setProcessorOfflineNumber(processorOfflineNumber);
        workTypeNumberVo.setProcessorOnlineNumber(processorOnlineNumber);
        workTypeNumberVo.setProcessorNoDeviceNumber(processorNoDeviceNumber);

        return workTypeNumberVo;
    }

    @Override
    public CarWorkTypeNumberVo getCarTypeNumber(JSONObject params) throws HssException {
        CarWorkTypeNumberVo carWorkTypeNumberVo = new CarWorkTypeNumberVo();
        List<CarAndWorkTypeVo> carAndWorkTypeList = elementTotalMapper.getCarAndWorkType();
        List<CarAndWorkTypeVo> carAndWorkTypeStreamList = carAndWorkTypeList.stream().filter(carAndWorkTypeVo -> null != carAndWorkTypeVo.getCarTypeName() && carAndWorkTypeVo.getCarTypeName().equals("转运车")).collect(Collectors.toList());
        carWorkTypeNumberVo.setTransportTruckNumber(carAndWorkTypeStreamList.size());

        List<TlEquip> tlEquipList = tlEquipService.list();
        Map<Object, List<TlEquip>> tlEquipCollect = tlEquipList.stream().filter(item -> StringUtils.isNotEmpty(item.getBindobjid())).collect(Collectors.groupingBy(TlEquip::getBindobjid));


        Integer transportTruckOnlineNumber = 0;
        Integer transportTruckOfflineNumber = 0;
        for (CarAndWorkTypeVo carAndWorkTypeVo : carAndWorkTypeStreamList) {
            List<TlEquip> tlEquips = tlEquipCollect.get(carAndWorkTypeVo.getCarId());
            if (null != tlEquips) {
                transportTruckOnlineNumber += (int) tlEquips.stream().filter(tlEquip -> (null != tlEquip.getOnlinestatus() && tlEquip.getOnlinestatus().equals("0")) && (null != tlEquip.getEquiptypeid() && tlEquip.getEquiptypeid().equals("252b781c1a454e042fe6531950f80b12"))).count();
                transportTruckOfflineNumber += (int) tlEquips.stream().filter(tlEquip -> (null != tlEquip.getOnlinestatus() && tlEquip.getOnlinestatus().equals("1")) && (null != tlEquip.getEquiptypeid() && tlEquip.getEquiptypeid().equals("252b781c1a454e042fe6531950f80b12"))).count();
            }
        }
        Integer transportTruckNoDeviceNumber = carAndWorkTypeStreamList.size() - transportTruckOnlineNumber - transportTruckOfflineNumber;
        carWorkTypeNumberVo.setTransportTruckNoDeviceNumber(transportTruckNoDeviceNumber);
        carWorkTypeNumberVo.setTransportTruckOnlineNumber(transportTruckOnlineNumber);
        carWorkTypeNumberVo.setTransportTruckOfflineNumber(transportTruckOfflineNumber);

        return carWorkTypeNumberVo;
    }

    @Override
    public ElementsList elementsList(JSONObject params) throws HssException {
        ElementsList elementsList = new ElementsList();
        /**
         * 车辆汇总
         */
        Integer totalOnlineNumCar = 0;
        Integer totalNumCar = 0;
        List<TlCar> tlCarList = tlCarMapper.selectList(new QueryWrapper<>());
        Map<String, TlCar> tlCarCollect = tlCarList.stream().collect(Collectors.groupingBy(TlCar::getId, Collectors.collectingAndThen(Collectors.toList(), tlCar -> tlCar.get(0))));

        Map<String, List<TlCar>> tlCarCollectByType = tlCarList.stream().filter(item -> StringUtils.isNotEmpty(item.getCartypeid())).collect(Collectors.groupingBy(TlCar::getCartypeid));

        List<TlCarType> tlCarTypeList = tlCarTypeMapper.selectList(new QueryWrapper<>());
        Map<String, TlCarType> tlCarTypeCollect = tlCarTypeList.stream().collect(Collectors.groupingBy(TlCarType::getId, Collectors.collectingAndThen(Collectors.toList(), tlCarTypes -> tlCarTypes.get(0))));

        QueryWrapper<TlEquip> tlEquipQueryWrapper = new QueryWrapper<>();
        tlEquipQueryWrapper.lambda().eq(TlEquip::getOnlinestatus, "0");
        List<TlEquip> tlEquipList = tlEquipMapper.selectList(tlEquipQueryWrapper);

        List<TlEquip> tlCarEquipList = tlEquipList.stream()
                .filter(item -> StringUtils.isNotEmpty(item.getBindobjid()))
                .filter(item -> "252b781c1a454e042fe6531950f80b12".equals(item.getEquiptypeid()))
                .collect(Collectors.toList());
        // 更新设备表上的车辆类型id
        tlCarEquipList.forEach(t -> {
            t.setBindtypeitem("");
            if (null != tlCarCollect.get(t.getBindobjid())) {
                t.setBindtypeitem(tlCarCollect.get(t.getBindobjid()).getCartypeid());
            }
        });
        Map<String, List<TlEquip>> tlCarEquipCollect = tlCarEquipList.stream().collect(Collectors.groupingBy(TlEquip::getBindtypeitem));
        List<ElementsVo> carElementsVoList = new ArrayList<>();
        tlCarCollectByType.keySet().forEach(t -> {
            ElementsVo elementsVo = new ElementsVo();
            elementsVo.setCarTypeId(t);
            elementsVo.setCarType("");
            if (null != tlCarTypeCollect.get(t)) {
                elementsVo.setCarType(tlCarTypeCollect.get(t).getTypename());
                elementsVo.setCarIcon(tlCarTypeCollect.get(t).getCaricon());
            }
            carElementsVoList.add(elementsVo);
        });

        carElementsVoList.forEach(t -> {
            t.setCarNum(0);
            if (null != tlCarCollectByType.get(t.getCarTypeId())) {
                t.setCarNum(tlCarCollectByType.get(t.getCarTypeId()).size());
            }
            t.setCarOnlineNum(0);
            if (null != tlCarEquipCollect.get(t.getCarTypeId())) {
                t.setCarOnlineNum(tlCarEquipCollect.get(t.getCarTypeId()).size());
            }
        });

        for (ElementsVo elementsVo : carElementsVoList) {
            totalOnlineNumCar += null == elementsVo.getCarOnlineNum() ? 0 : elementsVo.getCarOnlineNum();
            totalNumCar += null == elementsVo.getCarNum() ? 0 : elementsVo.getCarNum();
        }
        elementsList.setTotalNumCar(totalNumCar);
        elementsList.setTotalOnlineNumCar(totalOnlineNumCar);
        elementsList.setCarElementsList(carElementsVoList);


        /**
         * 人员汇总
         */
        Integer totalOnlineNumEmp = 0;
        Integer totalNumEmp = 0;

        List<TlEmployee> tlEmployeeList = tlEmployeeMapper.selectList(new QueryWrapper<>());

        Map<String, TlEmployee> stringTlEmployeeMap = tlEmployeeList.stream().collect(Collectors.groupingBy(TlEmployee::getId, Collectors.collectingAndThen(Collectors.toList(), tlEmployees -> tlEmployees.get(0))));

        Map<String, List<TlEmployee>> stringListMap = tlEmployeeList.stream().filter(item -> StringUtils.isNotEmpty(item.getWorktype())).collect(Collectors.groupingBy(TlEmployee::getWorktype));

        List<TlWorkType> tlWorkTypeList = tlWorkTypeMapper.selectList(new QueryWrapper<>());
        Map<String, TlWorkType> stringTlWorkTypeMap = tlWorkTypeList.stream().collect(Collectors.groupingBy(TlWorkType::getId, Collectors.collectingAndThen(Collectors.toList(), tlWorkTypes -> tlWorkTypes.get(0))));

        List<TlEquip> tlEmpEquipList = tlEquipList.stream()
                .filter(item -> StringUtils.isNotEmpty(item.getBindobjid()))
                .filter(item -> "dc605bf7800b204e3015ac977542e66b".equals(item.getEquiptypeid()))
                .collect(Collectors.toList());

        tlEmpEquipList.forEach(t -> {
            t.setBindtypeitem("");
            if (null != stringTlEmployeeMap.get(t.getBindobjid())) {
                t.setBindtypeitem(stringTlEmployeeMap.get(t.getBindobjid()).getWorktype());
            }
        });
        Map<String, List<TlEquip>> tlEmpEquipCollect = tlEmpEquipList.stream().collect(Collectors.groupingBy(TlEquip::getBindtypeitem));

        List<ElementsVo> empElementsVoList = new ArrayList<>();
        stringListMap.keySet().forEach(t -> {
            ElementsVo elementsVo = new ElementsVo();
            elementsVo.setEmpTypeId(t);
            elementsVo.setEmpType("");
            if (null != stringTlWorkTypeMap.get(t)) {
                elementsVo.setEmpType(stringTlWorkTypeMap.get(t).getWorktype());
                elementsVo.setEmpIcon(stringTlWorkTypeMap.get(t).getEmployeeicon());
            }
            empElementsVoList.add(elementsVo);
        });

        empElementsVoList.forEach(t -> {
            t.setEmpNum(0);
            if (null != stringListMap.get(t.getEmpTypeId())) {
                t.setEmpNum(stringListMap.get(t.getEmpTypeId()).size());
            }
            t.setEmpOnlineNum(0);
            if (null != tlEmpEquipCollect.get(t.getEmpTypeId())) {
                t.setEmpOnlineNum(tlEmpEquipCollect.get(t.getEmpTypeId()).size());
            }
        });
        for (ElementsVo elementsVo : empElementsVoList) {
            totalOnlineNumEmp += null == elementsVo.getEmpOnlineNum() ? 0 : elementsVo.getEmpOnlineNum();
            totalNumEmp += null == elementsVo.getEmpNum() ? 0 : elementsVo.getEmpNum();
        }
        elementsList.setTotalNumEmp(totalNumEmp);
        elementsList.setTotalOnlineNumEmp(totalOnlineNumEmp);
        elementsList.setEmployeeElementsList(empElementsVoList);
        /**
         * 设施
         */
        Integer totalOnlineNumFac = 0;
        Integer totalNumFac = 0;
        List<FacilitiesElements> facilitiesElementsList = elementTotalMapper.getFacilitiesNumber();
        for (FacilitiesElements facilitiesElements : facilitiesElementsList) {
            if (!"垃圾桶".equals(facilitiesElements.getFacilitiesType())) {
                totalOnlineNumFac += null == facilitiesElements.getOnlineNum() ? 0 : facilitiesElements.getOnlineNum();
                totalNumFac += facilitiesElements.getNum();
            }
        }
        elementsList.setTotalNumFac(totalNumFac);
        elementsList.setTotalOnlineNumFac(totalOnlineNumFac);
        elementsList.setFacilitiesElementsList(facilitiesElementsList);
        /**
         * 古木
         */
        Integer totalOnlineNumTree = 0;
        Integer totalNumTree = 0;
        List<OldTreesElements> oldTreesElementsList = elementTotalMapper.getOldTreesNumber();
        for (OldTreesElements oldTreesElements : oldTreesElementsList) {
            totalOnlineNumTree += null == oldTreesElements.getOnlineNum() ? 0 : oldTreesElements.getOnlineNum();
            totalNumTree += oldTreesElements.getNum();
        }
        elementsList.setTotalNumTree(totalNumTree);
        elementsList.setTotalOnlineNumTree(totalOnlineNumTree);
        elementsList.setOldTreesElementsList(oldTreesElementsList);
        /**
         * 园林
         */
        Integer totalOnlineNumGar = 0;
        Integer totalNumGar = 0;
        List<GardensElements> gardensElementsList = elementTotalMapper.getGardensNumber();
        for (GardensElements gardensElements : gardensElementsList) {
            totalOnlineNumFac += null == gardensElements.getOnlineNum() ? 0 : gardensElements.getOnlineNum();
            totalNumGar += gardensElements.getNum();
        }
        elementsList.setTotalNumGar(totalNumGar);
        elementsList.setTotalOnlineNumGar(totalOnlineNumGar);
        elementsList.setGardensElementsList(gardensElementsList);

        return elementsList;
    }


    public CarJobType getCarJobType(TlCar tlCar) {
        CarJobType carJobType = new CarJobType();
        TlCar tlCarType = tlCarMapper.selectById(tlCar.getId());
        Map<String, List<TlOperation>> tlOperationCollect = tlOperationMapper.selectList(new QueryWrapper<>()).stream().collect(Collectors.groupingBy(TlOperation::getId));
        if (null != tlCarType) {
            List<TlOperation> tlOperationList = tlOperationCollect.get(tlCarType.getCarcategory());
            if (null != tlOperationList) {
                List<TlOperation> jxqsCollect = tlOperationList.stream().filter(tlOperation -> null != tlOperation.getOperationtype() && (tlOperation.getOperationtype().equals("清扫作业") || tlOperation.getOperationtype().equals("洒水作业"))).collect(Collectors.toList());
                if (!jxqsCollect.isEmpty()) {
                    carJobType.setJobType(2);
                }
                List<TlOperation> ljqyCollect = tlOperationList.stream().filter(tlOperation -> null != tlOperation.getOperationtype() && tlOperation.getOperationtype().equals("垃圾清运")).collect(Collectors.toList());
                if (!ljqyCollect.isEmpty()) {
                    carJobType.setJobType(3);
                }
                List<TlOperation> ljzyCollect = tlOperationList.stream().filter(tlOperation -> null != tlOperation.getOperationtype() && tlOperation.getOperationtype().equals("垃圾转运")).collect(Collectors.toList());
                if (!ljzyCollect.isEmpty()) {
                    carJobType.setJobType(4);
                }
            }
        }

        return carJobType;
    }

    @Override
    public ElementsListByAppVo  getElementsListByApp() {
        ElementsListByAppVo elementsListByAppVo = new ElementsListByAppVo();
        /**
         * 车辆汇总
         */
        Integer totalOnlineNumCar = 0;
        Integer totalNumCar = 0;
        List<TlCar> tlCarList = tlCarMapper.selectList(new QueryWrapper<>());
        Map<String, TlCar> tlCarCollect = tlCarList.stream().collect(Collectors.groupingBy(TlCar::getId, Collectors.collectingAndThen(Collectors.toList(), tlCar -> tlCar.get(0))));

        Map<String, List<TlCar>> tlCarCollectByType = tlCarList.stream().filter(item -> StringUtils.isNotEmpty(item.getCartypeid())).collect(Collectors.groupingBy(TlCar::getCartypeid));

        List<TlCarType> tlCarTypeList = tlCarTypeMapper.selectList(new QueryWrapper<>());
        Map<String, TlCarType> tlCarTypeCollect = tlCarTypeList.stream().collect(Collectors.groupingBy(TlCarType::getId, Collectors.collectingAndThen(Collectors.toList(), tlCarTypes -> tlCarTypes.get(0))));

        QueryWrapper<TlEquip> tlEquipQueryWrapper = new QueryWrapper<>();
        tlEquipQueryWrapper.lambda().eq(TlEquip::getOnlinestatus, "0");
        List<TlEquip> tlEquipList = tlEquipMapper.selectList(tlEquipQueryWrapper);

        List<TlEquip> tlCarEquipList = tlEquipList.stream()
                .filter(item -> StringUtils.isNotEmpty(item.getBindobjid()))
                .filter(item -> "252b781c1a454e042fe6531950f80b12".equals(item.getEquiptypeid()))
                .collect(Collectors.toList());
        // 更新设备表上的车辆类型id
        tlCarEquipList.forEach(t -> {
            t.setBindtypeitem("");
            if (null != tlCarCollect.get(t.getBindobjid())) {
                t.setBindtypeitem(tlCarCollect.get(t.getBindobjid()).getCartypeid());
            }
        });
        Map<String, List<TlEquip>> tlCarEquipCollect = tlCarEquipList.stream().collect(Collectors.groupingBy(TlEquip::getBindtypeitem));
        List<ElementsVo> carElementsVoList = new ArrayList<>();
        tlCarCollectByType.keySet().forEach(t -> {
            ElementsVo elementsVo = new ElementsVo();
            elementsVo.setCarTypeId(t);
            elementsVo.setCarType("");
            if (null != tlCarTypeCollect.get(t)) {
                elementsVo.setCarType(tlCarTypeCollect.get(t).getTypename());
                elementsVo.setCarIcon(tlCarTypeCollect.get(t).getCaricon());
            }
            carElementsVoList.add(elementsVo);
        });

        carElementsVoList.forEach(t -> {
            t.setCarNum(0);
            if (null != tlCarCollectByType.get(t.getCarTypeId())) {
                t.setCarNum(tlCarCollectByType.get(t.getCarTypeId()).size());
            }
            t.setCarOnlineNum(0);
            if (null != tlCarEquipCollect.get(t.getCarTypeId())) {
                t.setCarOnlineNum(tlCarEquipCollect.get(t.getCarTypeId()).size());
            }
        });

        for (ElementsVo elementsVo : carElementsVoList) {
            totalOnlineNumCar += null == elementsVo.getCarOnlineNum() ? 0 : elementsVo.getCarOnlineNum();
            totalNumCar += null == elementsVo.getCarNum() ? 0 : elementsVo.getCarNum();
        }
        List<TlCar> tlCarByAttendanceList = tlCarList.stream().filter(tlCar -> null != tlCar.getAttendance() && tlCar.getAttendance() == 0).collect(Collectors.toList());

        QueryWrapper<AlarmCar> alarmCarQueryWrapper = new QueryWrapper<>();
        alarmCarQueryWrapper.lambda().like(AlarmCar::getAlarmTime, StringUtils.dateToStr(new Date(), "yyyy-MM-dd"));
        List<AlarmCar> alarmCarList = alarmCarMapper.selectList(alarmCarQueryWrapper);
        Map<String, List<AlarmCar>> alarmCarMap = alarmCarList.stream().collect(Collectors.groupingBy(AlarmCar::getCarId));

        QueryWrapper<CarViolation> carViolationQueryWrapper = new QueryWrapper<>();
        carViolationQueryWrapper.lambda().like(CarViolation::getTime, StringUtils.dateToStr(new Date(), "yyyy-MM-dd"));
        List<CarViolation> carViolationList = carViolationMapper.selectList(carViolationQueryWrapper);
        Map<String, List<CarViolation>> carViolationMap = carViolationList.stream().collect(Collectors.groupingBy(CarViolation::getCarId));

        QueryWrapper<RptCarWork> rptCarWorkQueryWrapper = new QueryWrapper<>();
        rptCarWorkQueryWrapper.lambda().eq(RptCarWork::getWorkDate, StringUtils.dateToStr(new Date(), "yyyy-MM-dd"));
        List<RptCarWork> rptCarWorkList = rptCarWorkMapper.selectList(rptCarWorkQueryWrapper);
        Set<String> carList = new HashSet<>();

        Integer alarmCarNumber = 0;
        Integer carViolationNumber = 0;
        for (RptCarWork rptCarWork : rptCarWorkList) {
            carList.add(rptCarWork.getCarId());
            List<AlarmCar> alarmCarList1 = alarmCarMap.get(rptCarWork.getCarId());
            if (null != alarmCarList1) {
                alarmCarNumber += alarmCarList1.size();
            }
            List<CarViolation> carViolationList1 = carViolationMap.get(rptCarWork.getCarId());
            if (null != carViolationList1) {
                carViolationNumber += carViolationList1.size();
            }
        }
        Integer carAbnormalNumber = alarmCarNumber + carViolationNumber;
        elementsListByAppVo.setAttendanceNumber(tlCarByAttendanceList.size());
        elementsListByAppVo.setAbnormalNumber(carAbnormalNumber);
        elementsListByAppVo.setWorkPlanNumber(carList.size());
        elementsListByAppVo.setTotalNum(totalNumCar);
        elementsListByAppVo.setTotalOnlineNum(totalOnlineNumCar);
        elementsListByAppVo.setName("车辆");
//        elementsList.setCarElementsList(carElementsVoList);


        /**
         * 人员汇总
         */
        Integer totalOnlineNumEmp = 0;
        Integer totalNumEmp = 0;

        List<TlEmployee> tlEmployeeList = tlEmployeeMapper.selectList(new QueryWrapper<>());

        Map<String, TlEmployee> stringTlEmployeeMap = tlEmployeeList.stream().collect(Collectors.groupingBy(TlEmployee::getId, Collectors.collectingAndThen(Collectors.toList(), tlEmployees -> tlEmployees.get(0))));

        Map<String, List<TlEmployee>> stringListMap = tlEmployeeList.stream().filter(item -> StringUtils.isNotEmpty(item.getWorktype())).collect(Collectors.groupingBy(TlEmployee::getWorktype));

        List<TlWorkType> tlWorkTypeList = tlWorkTypeMapper.selectList(new QueryWrapper<>());
        Map<String, TlWorkType> stringTlWorkTypeMap = tlWorkTypeList.stream().collect(Collectors.groupingBy(TlWorkType::getId, Collectors.collectingAndThen(Collectors.toList(), tlWorkTypes -> tlWorkTypes.get(0))));

        List<TlEquip> tlEmpEquipList = tlEquipList.stream()
                .filter(item -> StringUtils.isNotEmpty(item.getBindobjid()))
                .filter(item -> "dc605bf7800b204e3015ac977542e66b".equals(item.getEquiptypeid()))
                .collect(Collectors.toList());

        tlEmpEquipList.forEach(t -> {
            t.setBindtypeitem("");
            if (null != stringTlEmployeeMap.get(t.getBindobjid())) {
                t.setBindtypeitem(stringTlEmployeeMap.get(t.getBindobjid()).getWorktype());
            }
        });
        Map<String, List<TlEquip>> tlEmpEquipCollect = tlEmpEquipList.stream().collect(Collectors.groupingBy(TlEquip::getBindtypeitem));

        List<ElementsVo> empElementsVoList = new ArrayList<>();
        stringListMap.keySet().forEach(t -> {
            ElementsVo elementsVo = new ElementsVo();
            elementsVo.setEmpTypeId(t);
            elementsVo.setEmpType("");
            if (null != stringTlWorkTypeMap.get(t)) {
                elementsVo.setEmpType(stringTlWorkTypeMap.get(t).getWorktype());
                elementsVo.setEmpIcon(stringTlWorkTypeMap.get(t).getEmployeeicon());
            }
            empElementsVoList.add(elementsVo);
        });

        empElementsVoList.forEach(t -> {
            t.setEmpNum(0);
            if (null != stringListMap.get(t.getEmpTypeId())) {
                t.setEmpNum(stringListMap.get(t.getEmpTypeId()).size());
            }
            t.setEmpOnlineNum(0);
            if (null != tlEmpEquipCollect.get(t.getEmpTypeId())) {
                t.setEmpOnlineNum(tlEmpEquipCollect.get(t.getEmpTypeId()).size());
            }
        });
        for (ElementsVo elementsVo : empElementsVoList) {
            totalOnlineNumEmp += null == elementsVo.getEmpOnlineNum() ? 0 : elementsVo.getEmpOnlineNum();
            totalNumEmp += null == elementsVo.getEmpNum() ? 0 : elementsVo.getEmpNum();
        }
        List<TlEmployee> tlEmployeeByAttendanceList = tlEmployeeList.stream().filter(tlEmployee -> null != tlEmployee.getAttendance() && tlEmployee.getAttendance() == 0).collect(Collectors.toList());

        QueryWrapper<RptEmployeeWork> rptEmployeeWorkQueryWrapper = new QueryWrapper<>();
        rptEmployeeWorkQueryWrapper.lambda().eq(RptEmployeeWork::getWorkDate, StringUtils.dateToStr(new Date(), "yyyy-MM-dd"));
        List<RptEmployeeWork> rptEmployeeWorkList = rptEmployeeWorkMapper.selectList(rptEmployeeWorkQueryWrapper);

        QueryWrapper<AlarmPerson> alarmPersonQueryWrapper = new QueryWrapper<>();
        alarmPersonQueryWrapper.lambda().like(AlarmPerson::getAlarmTime, StringUtils.dateToStr(new Date(), "yyyy-MM-dd"));
        List<AlarmPerson> alarmPersonList = alarmPersonMapper.selectList(alarmPersonQueryWrapper);
        Map<String, List<AlarmPerson>> alarmPersonMap = alarmPersonList.stream().collect(Collectors.groupingBy(AlarmPerson::getPersonId));

        QueryWrapper<DlbjViolation> dlbjViolationQueryWrapper = new QueryWrapper<>();
        dlbjViolationQueryWrapper.lambda().like(DlbjViolation::getDate, StringUtils.dateToStr(new Date(), "yyyy-MM-dd"));
        List<DlbjViolation> dlbjViolationList = dlbjViolationMapper.selectList(dlbjViolationQueryWrapper);
        Map<String, List<DlbjViolation>> dlbjViolationMap = dlbjViolationList.stream().collect(Collectors.groupingBy(DlbjViolation::getPersonId));

        Integer alarmEmpNumber = 0;
        Integer empViolationNumber = 0;
        Set<String> empList = new HashSet<>();
        for (RptEmployeeWork rptEmployeeWork : rptEmployeeWorkList) {
            empList.add(rptEmployeeWork.getEmployeeId());
            List<AlarmPerson> alarmPersonList1 = alarmPersonMap.get(rptEmployeeWork.getEmployeeId());
            if (null != alarmPersonList1) {
                alarmEmpNumber += alarmPersonList1.size();
            }

            List<DlbjViolation> dlbjViolationList1 = dlbjViolationMap.get(rptEmployeeWork.getEmployeeId());
            if (null != dlbjViolationList1) {
                empViolationNumber += dlbjViolationList1.size();
            }
        }
        Integer empAbnormalNumber = alarmEmpNumber + empViolationNumber;
        elementsListByAppVo.setAttendanceNumber(tlEmployeeByAttendanceList.size());
        elementsListByAppVo.setAbnormalNumber(empAbnormalNumber);
        elementsListByAppVo.setWorkPlanNumber(empList.size());
        elementsListByAppVo.setTotalNum(totalNumEmp);
        elementsListByAppVo.setTotalOnlineNum(totalOnlineNumEmp);
        elementsListByAppVo.setName("车辆");

        return elementsListByAppVo;
    }

}

